package com.smile.ye.common.security;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.smile.ye.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {


    @Autowired
    RedisTemplate redisTemplate;
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        try{
            String token = request.getHeader("Authorization");
            if(StringUtils.isBlank(token)){
                chain.doFilter(request,response);
                return;
            }
            if(token.startsWith("Bearer ")){
               String username = JwtUtils.verifyToken(token.substring(7));
               if(!StringUtils.isBlank(username)){
                       UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username,null,null);
                       SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
               }
            }
        }catch (Exception e){
            System.out.println("jwt验证失败");
            e.printStackTrace();
        }
        chain.doFilter(request,response);
    }
}